﻿using System;
using IQIGame.Onigao.Game;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class GM : MonoBehaviour
    {
        static private GM Instance { get; set; }

        [SerializeField] private bool m_ActiveGM = true;
        private Rect m_Rect;
        private int m_WindowId = 0;

        private GUISkin m_Skin = null;
        private float m_WindowScale = 1f;
        private Rect m_DragRect;

        private void Awake()
        {
            m_WindowId = this.gameObject.GetInstanceID();

            int width = 120;
            int height = 80;
            int x = 10;
            int y = Screen.height - height - 10;
            m_Rect = new Rect(x, y, width, height);
            m_DragRect = new Rect(0f, 0f, float.MaxValue, 25f);

            Instance = this;
        }

        private void OnGUI()
        {
            if (!m_ActiveGM || Instance == null)
            {
                return;
            }
            DrawWindow(DrawingWindow);
            //DrawingWindow();
        }

        private void DrawWindow(Action onDraw)
        {
            GUISkin cachedGuiSkin = GUI.skin;
            Matrix4x4 cachedMatrix = GUI.matrix;

            GUI.skin = m_Skin;
            GUI.matrix = Matrix4x4.Scale(new Vector3(m_WindowScale, m_WindowScale, 1f));
            onDraw?.Invoke();
            GUI.matrix = cachedMatrix;
            GUI.skin = cachedGuiSkin;
        }

        private void DrawingWindow()
        {
            m_Rect = GUILayout.Window(m_WindowId, m_Rect, DrawGMWindow, "<b>GMWindow</b>");
        }

        private void DrawGMWindow(int windowId)
        {
            if (m_WindowId != windowId)
                return;
            GUI.DragWindow(m_DragRect);
            GUILayout.Space(5);
            Color32 color = Color.white;
            if (GUILayout.Button("GM", GUILayout.Width(100f), GUILayout.Height(40f)))
            {
                ManagerCenter.UI.ShowWindow<UIGMList>();
            }
        }

        static public void CloseGM()
        {
            if (Instance != null)
                Instance.m_ActiveGM = false;
        }

        static public void ShowGm()
        {
            if (Instance != null)
                Instance.m_ActiveGM = true;
        }
    }
}
